import socket
import os
import time
import threading
import queue
# def tcp_client():
#     server_address = ('172.17.0.1', 8090)
#     while True:
#         client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#         try:
#             print(f"连接到服务器 {server_address}...")
#             client_socket.connect(server_address)
#             cs_file_path = '/root/paraformer/example/dog.bin'
#
#             if os.path.exists(cs_file_path):
#                 while True:
#                     with open(cs_file_path, 'rb') as cs_file:
#                         while True:
#                             cs_data = cs_file.read(1024)
#                             if not cs_data:
#                                 break
#                             client_socket.sendall(cs_data)
#                             print(cs_data)
#                             # 清空文件内容，确保写入的数据不会重复发送
#                             open(cs_file_path, 'wb').close()
#                             confirmation = client_socket.recv(1024)
#                             print(confirmation.decode('utf-8'))
#
#                     time.sleep(0.1)
#
#             else:
#                 print(f"文件 {cs_file_path} 不存在")
#
#         except Exception as e:
#             print(f"传输过程中发生错误: {e}")
#             print("将在2秒后重新尝试连接...")
#             time.sleep(2)
#
#         finally:
#             client_socket.close()
#             print("连接已关闭")
def tcp_client(dogmessage_queue):
    server_address = ('172.17.0.1', 8090)

    while True:
        try:
            # 首先检查队列是否有数据，如果为空则跳过这次循环
            if dogmessage_queue.empty():
                time.sleep(0.1)  # 如果队列为空，稍等一下，避免忙等待
                continue

            # 获取队列中的数据，设置超时以防止阻塞过久
            data = dogmessage_queue.get(timeout=0.1)

            # 确保 data 是字节类型
            if isinstance(data, str):
                data = data.encode('utf-8')

            # 创建 socket 连接到服务器
            client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            print(f"连接到服务器 {server_address}...")
            client_socket.connect(server_address)

            # 发送数据
            client_socket.sendall(data)
            print(f"发送的数据: {data}")

            # 接收确认信息
            confirmation = client_socket.recv(1024)
            print(f"服务器返回: {confirmation.decode('utf-8')}")

        except queue.Empty:
            # 这种情况下我们不需要打印错误，只需跳过
            continue

        except Exception as e:
            # 捕获所有其他异常并打印错误信息
            print(f"传输过程中发生错误: {e}")
            print("将在2秒后重新尝试连接...")
            time.sleep(2)

        finally:
            # 确保关闭 socket 连接
            try:
                client_socket.close()
                print("连接已关闭")
            except NameError:
                # 如果 client_socket 没有成功创建，则跳过关闭步骤
                pass

def tcp_client_receive():
    server_address = ('172.17.0.1', 8091)
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        print(f"连接到服务器 {server_address}...")
        client_socket.connect(server_address)

        while True:
            try:
                received_data = client_socket.recv(1024)
                if received_data:
                    print(f"接收到的数据: {received_data.decode('utf-8')}")
                    cs_file_path = '/root/paraformer/example/input.bin'
                    with open(cs_file_path, 'w') as cs_file:
                        cs_file.write('person')
            except Exception as e:
                print(f"接收过程中发生错误: {e}")
                break

    except Exception as e:
        print(f"连接过程中发生错误: {e}")

    finally:
        client_socket.close()
        print("连接已关闭")

if __name__ == "__main__":
    thread1 = threading.Thread(target=tcp_client)
    thread2 = threading.Thread(target=tcp_client_receive)

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()

